<!-- 留存分析 -->
<template>
  <div class="keep">
    <!-- <h2 class="title">留存分析</h2> -->
    <div class="card1">
      <div style="width:100%;background-color:#f2f2f2;height:42px;">
        <span style="margin-left:20px;line-height:42px;">留存分析</span>
      </div>
    </div>
    <el-row :guttter="20">
      <el-col :span="4">
        <el-card class="list-card">
          <h1 style="margin-top: 1px;">使用该模型已保存的图表</h1>
          <el-row>
            <li v-for="(item,index) in dataList" :key="index" class="list-title-li">
              <span class="list-title" @click="setCondition(item)">{{item.model_name}}<i
                  class="el-icon-close list-delete" @click="handleDelete(item)"></i></span>
            </li>
          </el-row>
        </el-card>
      </el-col>
      <el-col :span="19" style="background-color:#fff;margin-left:20px">
        <el-row class="info">
          <el-col :span="5">
            <h1>初始行为</h1>
            <el-select v-model="initialBehavior" placeholder="请选择">
              <el-option v-for="item in selectBehavior" :key="item.event_code" :label="item.event_name"
                :value="item.event_code">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="17">
            <h3>后续行为</h3>
            <el-select v-model="followUpBehavior" placeholder="请选择">
              <el-option v-for="item in selectBehavior" :key="item.event_code" :label="item.event_name"
                :value="item.event_code">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="2">
            <el-button type="text" style="margin-left: 27px;" @click="openVisible"><img src="@/assets/icon-save.png"
                class="save-icon" /><span style="float: right;margin-top: 7px;margin-left: 4px;">保存</span></el-button>
          </el-col>
        </el-row>
        <el-divider></el-divider>
        <div class="filterCondition">
          <el-row>
            <el-col :span="20">
              <h3>过滤条件</h3>
              <div class="select">
                <el-select @change="changeSelect" v-model="modelFilterSelecterValue" placeholder="请选择">
                  <el-option v-for="(item,i) in filterSelecter" :key="i" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
                <span>等于</span>
                <el-select @change="changefilterTabs" v-model="filterTabsModelValue" placeholder="请选择">
                  <el-option v-for="item in filterTabs" :key="item.name" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
                <div class="tool">
                  <i @click="addCondition" class="el-icon-plus" style="margin-left:4px;"></i>
                  <i @click="removeCondition" class="el-icon-minus" style="margin-left:4px;"></i>
                </div>
              </div>
            </el-col>
            <el-col :span="2" :offset="2">
              <el-button @click="getTablesData" class="findClass">查询</el-button>
            </el-col>
          </el-row>
          <el-row class="addCondition" v-for="(value,i) in conditionGather" :key="i">
            <el-col :span="20">
              <div class="select">
                <el-select @change="changeAddSelect(value)" v-model="filterMain[value]" placeholder="请选择">
                  <el-option v-for="(item,i) in filterSelecter" :key="i" :label="item.name" :value="item.name">
                  </el-option>
                </el-select>
                <span>等于</span>
                <el-select @change="changeSelectTabs" v-model="filterTabsAddvalue[value]" placeholder="请选择">
                  <el-option v-for="item in filterTabsSelect[value]" :key="item.name" :label="item.name"
                    :value="item.name">
                  </el-option>
                </el-select>
                <div class="tool">
                  <i @click="addCondition" class="el-icon-plus" style="margin-left:4px;"></i>
                  <i @click="removeCondition" class="el-icon-minus" style="margin-left:4px;"></i>
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="divider"></div>
        <div class="tables">
          <el-row class="datestyle">
            <el-date-picker v-model="dates" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
              start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-row>
          <el-row class="tableWrapper">
            <el-table :data="tablesData" border height="550" style="width:100%" v-loading="loading">
              <el-table-column prop="dateValue" label="日期" width="180">
              </el-table-column>
              <el-table-column v-for='(item,i) in tablesData' :key="i" :label="i===0?'当日':'第'+i+'日'"
                show-overflow-tooltip>
                <template slot-scope="scope">
                  <span v-if="scope.row.subs[i]" style="text-align:center">

                    {{scope.row.subs[i]['people']+'人'}}
                    <br>
                    {{scope.row.subs[i]['percent']+'%'}}

                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <el-dialog title="保存图表" :visible.sync="saveVisible" width="30%">
      <span style="float:left;font-size:13px">图表名称</span>
      <el-input v-model="modelName" placeholder="请输入图表名称"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="saveVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSave">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        loading: false,
        selectBehavior: [],
        initialBehavior: '',
        followUpBehavior: '',
        conditionGather: [],
        filterSelecter: [],
        modelFilterSelecterValue: '',
        //条件标签详细信息
        filterTabs: [],
        filterTabsModelValue: '',
        saveVisible: false,
        modelName: '',
        mainFilterParams: [],
        filterMain: {},
        filterTabsAddvalue: {},
        dataList: [],
        filterTabsSelect: {
          host0: [],
          host1: [],
          host2: [],
          host3: [],
          host4: [],
          host5: [],
          host6: [],
          host7: [],
          host8: [],
          host9: [],
          host10: [],
          host11: []
        },
        findDataMax: [],
        dates: [],
        tablesData: []
      }
    },
    //生命周期 - 创建完成（访问当前this实例）
    created() {
      this.dates = [this.fun_date, this.getDefaultDate]
      this.getList()

    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
      this.getInfoBehavior()
      this.getFilterInfo()
    },
    methods: {
      //初始数据
      async getInfoBehavior() {
        const res = await this.$http.post('http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/eventList')
        if (res.data.code !== 0) return
        this.selectBehavior = res.data.data
      },
      //添加条件
      addCondition() {
        const name = 'host' + this.conditionGather.length
        this.conditionGather.push(name)
      },
      //移除条件
      removeCondition() {
        const value = this.conditionGather[this.conditionGather.length - 1]
        this.filterMain[value] = ''
        this.filterTabsSelect[value] = []
        this.filterTabsAddvalue[value] = ''
        this.conditionGather.splice(this.conditionGather.length - 1, 1)
        this.findDataMax.splice(this.findDataMax.length - 1, 1)
        console.log(this.findDataMax);
      },
      //条件数据
      async getFilterInfo() {
        const res = await this.$http.post(
          'http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListKey')
        if (res.data.code !== 1) return
        this.filterSelecter = res.data.data.list
      },
      async changeSelect() {
        console.log(this.modelFilterSelecterValue);
        this.filterTabs = await this.getFilterSelect(this.modelFilterSelecterValue)
        console.log(this.filterTabs);
      },
      async getFilterSelect(params) {
        const res = await this.$http.post(
          'http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=' + params)
        if (res.data.code !== 1) return
        return res.data.data.list
      },
      changefilterTabs() {
        const index = this.mainFilterParams.findIndex(item => {
          return item['type'] === 'host'
        })
        if (index !== -1) {
          this.mainFilterParams.splice(index, 1)
        }
        const data = this.filterTabs.filter(item => {
          return item.name === this.filterTabsModelValue
        })
        data.type = 'host'
        this.mainFilterParams.push(data)
        let host = this.mainFilterParams[0][0]
        this.findDataMax.push(host)
        console.log(this.findDataMax);
      },
      async changeAddSelect(value) {
        console.log(value)
        const res = await this.getFilterSelect(this.filterMain[value])
        this.filterTabsSelect[value] = res
      },
      changeSelectTabs() {
        //首次值，不会增加也不会减少，脱离三界之外。
        let host = []
        this.findDataMax = []
        const keys = Object.keys(this.filterTabsAddvalue)
        console.log(this.filterTabsAddvalue);
        console.log(this.filterTabsSelect);
        console.log(keys);
        if (this.mainFilterParams.length > 0) {
          host = this.mainFilterParams[0][0]
          this.findDataMax.push(host)
        }

        keys.forEach(item => {
          this.filterTabsSelect[item].forEach(value => {
            if (value.name === this.filterTabsAddvalue[item]) {
              //这里将拿到最终奥义，每次点击，都会形成
              this.findDataMax.push(value)
            }
          })
        })
      },
      async getTablesData() {
        this.loading = true
        let params = {
          eventCode: [{
            eventCode: this.initialBehavior
          }, {
            eventCode: this.followUpBehavior
          }],
          filterParameter: this.findDataMax,
          startDate: this.dates[0],
          endDate: this.dates[1]
        }
        const res = await this.$http.post(
          'http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/remainAnalysis', params)
        if (res.data.code !== 1) return
        this.tablesData = res.data.data.detailList
        this.loading = false
        console.log(this.tablesData);
      },
      //获取事件分析列表
      getList() {
        this.$http.post("http://127.0.0.1:8080/userprofile-platform/v1/modelList/listRemainModel", {}).then(res => {
          if (res.data.flag && res.data.code == 1) {
            this.dataList = res.data.data.list
          } else {
            this.$message.error(res.data.msg)
          }
        })
      },
      //打开判断
      openVisible() {
        console.log(this.filterTabsSelect)
        if (this.initialBehavior && this.followUpBehavior) {
          this.saveVisible = true
        } else {
          this.$message.error('初始行为或后续行为不得为空')
        }
      },
      //保存模型
      handleSave() {
        let params = {
          eventCode: [{
            eventCode: this.initialBehavior
          }, {
            eventCode: this.followUpBehavior
          }],
          filterParameter: this.findDataMax,
          startDate: this.dates[0],
          endDate: this.dates[1],
          modelName: this.modelName
        }
        this.$http.post("http://127.0.0.1:8080/userprofile-platform/v1/modelList/remainAnalysisModel", params).then(res => {
          if (res.data.code == 100) {
            this.$message.success(res.data.msg)
            this.saveVisible = false
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      },
      //删除
      handleDelete(item) {
        this.$confirm('确认删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const URL = "http://127.0.0.1:8080/userprofile-platform/v1/modelList/deleteRemainModel?modelId=" + item.model_id
          this.$http.post(URL, {}).then(res => {
            if (res.data.code == 100) {
              this.$message.success(res.data.msg)
              this.getList()
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }).catch(() => {

        })
      },
      //生成查询条件
      async setCondition(data) {
        this.conditionGather = []
        this.findDataMax = []
        const eventCode = JSON.parse(data.event_code)
        this.initialBehavior = eventCode[0].eventCode
        this.followUpBehavior = eventCode[1].eventCode
        const filterParameter = JSON.parse(data.filter_parameter)
        this.findDataMax = filterParameter
        for (let i = 0; i < filterParameter.length; i++) {
          const name = 'host' + i
          if (i >= 1) {
            this.conditionGather.push(name)
            await this.filterSelecter.forEach(item => {
              if (filterParameter[i].field == item.field) {
                this.filterMain[name] = item.name;
                this.$http.post(
                  'http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=' +
                  item.name).then(res => {
                  if (res.data.code == 1) {
                    this.filterTabsSelect[name] = res.data.data.list
                    this.filterTabsAddvalue[name] = filterParameter[i].name
                  }
                })
              }
            })
          } else {
            this.filterSelecter.forEach(item => {
              if (item.field == filterParameter[i].field) {
                this.modelFilterSelecterValue = item.name;
                this.$http.post(
                  'http://127.0.0.1:8080/userprofile-platform/v1/DataAnalysis/dropDownListValue?level_2_name=' +
                  item.name).then(res => {
                  if (res.data.code == 1) {
                    this.filterTabs = res.data.data.list
                    this.filterTabsModelValue = filterParameter[i].name
                  }
                })
              }
            })
          }
        }
      },
    },
    computed: {
      getDefaultDate() {
        const date = new Date()
        const y = date.getFullYear()
        const m = (date.getMonth() + 1 + '').padStart(2, '0')
        const d = (date.getDate() + '').padStart(2, '0')
        return y + '-' + m + '-' + d
      },
      fun_date() {
        var date1 = new Date(),
          time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate(); //time1表示当前时间
        var date2 = new Date(date1);
        date2.setDate(date1.getDate() - 7);
        var time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + date2.getDate();
        return time2;
      }
    }
  }

</script>
<style scoped>
  .card1 {
    text-align: left;
    font-size: 18px;
  }

  .keep .info {
    padding-bottom: 10px;
  }

  .keep .info .el-col {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-items: flex-start;
  }

  .keep .info .el-col:nth-of-type(1) {
    padding-left: 20px;
  }

  .filterCondition {
    padding-bottom: 10px;
    padding-left: 20px;
  }

  .filterCondition .el-row {
    display: flex;
    flex-direction: row;
  }

  .filterCondition .el-row .el-col {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-end;
  }

  .filterCondition .el-row .el-col .select {
    display: flex;
    align-items: center;
  }

  .filterCondition .el-row .el-col .select span {
    padding: 0px 10px;
  }

  .select .tool {
    padding: 0px 10px;
  }

  .addCondition {
    padding-top: 10px;
  }

  .tables {
    padding-left: 20px;
    display: flex;
    flex-direction: column;
  }

  .tables .datestyle {
    padding-top: 30px;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }

  .tables .tableWrapper {
    padding-top: 30px;
    display: flex;
    flex-direction: row;
    align-items: flex-start;
  }

  .title {
    text-align: left;
    padding-left: 20px;
    background-color: rgb(242, 242, 242);
    height: 42px;
    line-height: 42px;
    font-weight: 400;
    margin: 0;
    padding: 10px 20px;
  }

  .findClass {
    width: 68px;
    background-color: #3a4267;
    color: #fff;
    border-radius: 40px;
    margin-left: 26px
  }

  .list-card {
    height: 890px;
  }

  .list-title-li {
    list-style: none;
    text-align: left;
    margin-top: 10px;
  }

  .list-title {
    margin-left: 10px;
    color: #999;
    cursor: pointer;
  }

  .list-delete {
    float: right;
    margin-top: 3px;
    font-size: 17px;
    color: black;
    font-weight: 800;
    cursor: pointer;
  }

  .save-icon {
    width: 27px;
    height: 27px;
  }

  .el-dialog__wrapper /deep/ .el-dialog__title {
    line-height: 24px;
    font-size: 18px;
    color: #303133;
    float: left;
  }

  .el-dialog__wrapper /deep/ .el-dialog {
    position: relative;
    margin: 0 auto 50px;
    border-radius: 15px;
    -webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    width: 50%;
  }

  .divider {
    width: 100%;
    height: 23px;
    background: #F1F4F7;
  }

  .el-col-19 {
    width: 82%;
  }

  .el-divider--horizontal {
    display: block;
    height: 1px;
    width: 98%;
    margin: 24px 18px;
  }

</style>
